package com.diipo.weibo;

import com.diipo.weibo.utils.HttpUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView.ScaleType;

public class SettingActivity extends Activity{
	

	private String TAG = SettingActivity.class.getSimpleName();
	private Context mctx;
	private static final int DIALOG_WEBSITE_ADDRESS = 1;
	private SharedPreferences mPrefs;
	private ListView settingListView;
	private String mCheck_url = "/api/account/check_api.json?api_key=";
//	private View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
//	private EditText editAdress = (EditText) textEntryView.findViewById(R.id.url_address_edit);
	private View mTextEntryView ;
	private EditText mEditAdress;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// Hide title 
        requestWindowFeature( Window.FEATURE_NO_TITLE );
		setContentView(R.layout.setting_view);
		settingListView = (ListView) findViewById(R.id.setting_listview);
		mctx = this;
		mPrefs = getSharedPreferences(ConfigInfo.USER_PREFERENCES,MODE_PRIVATE);
		LayoutInflater factory = LayoutInflater.from(this);
		mTextEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
		mEditAdress = (EditText) mTextEntryView.findViewById(R.id.url_address_edit);
		settingListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if(0 == position){
					Log.e(" pyb ", " position = = 0 website");
					showDialog(DIALOG_WEBSITE_ADDRESS);
				}else if( 1 == position){
					Log.e(" pyb ", " position = = 1 about");
			    	Intent intent = new Intent(SettingActivity.this,AboutInfoActivity.class);
			    	startActivity(intent);	   
				}else{
					if(2 == position && ConfigInfo.IS_LOGOUT){
						Intent intent = new Intent(mctx,LoginActivity.class); //go  to the login UI
						startActivity(intent);
						finish();
					}else{
						exitApp();
					}
					Log.e(" pyb ", " position = 3 exit");
//					android.os.Process.killProcess(android.os.Process.myPid());  
				}
				Log.e(" pyb ", " position = " + position);
			}
		});
		settingListView.setAdapter(new EfficientAdapter(this));
	}
	
	private void exitApp(){
//		Home homeActivity = (Home) mctx;
//		homeActivity.finish();
//		
//		MsgActivity msgActivity = (MsgActivity) mctx;
//		msgActivity.finish();
//		
//		PrivateLetterActivity letterActivity = (PrivateLetterActivity) mctx;
//		letterActivity.finish();
//		
//		ContactsActivity contacts = (ContactsActivity) mctx;
//		contacts.finish();
//		
//		finish();
		
//		ConfigInfo.getInstanceContext().finish();
//		if(ConfigInfo.getInstanceHome()!= null){
//			ConfigInfo.getInstanceHome().finish();
//		}
//		if(ConfigInfo.getInstanceMsgActivity() != null){
//			ConfigInfo.getInstanceMsgActivity().finish();
//		}
//		
//		if(ConfigInfo.getInstancePrivateLetterActivity() != null){
//			ConfigInfo.getInstancePrivateLetterActivity().finish();
//		}
//		if(ConfigInfo.getInstanceContactsActivity()!= null){
//			ConfigInfo.getInstanceContactsActivity().finish();
//		}
		finish();
		
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putString(ConfigInfo.PREF_USERNAME, "");
		editor.putString(ConfigInfo.PREF_PASSWORD, "");
		editor.commit();
		
		if(ConfigInfo.getInstanceMainTabs() != null) ConfigInfo.getInstanceMainTabs().finish();
		ConfigInfo.IS_LOGOUT = true;
		Intent intent = new Intent(mctx,SettingActivity.class);
//		intent.putExtra(ConfigInfo.COMM.LOGOUT,"yes");
		startActivity(intent);
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_WEBSITE_ADDRESS:
        	 // This example shows how to add a custom layout to an AlertDialog
        	mEditAdress.setText(null);
        	mEditAdress.setText(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, ConfigInfo.COMM.CONST_SERVER_ADDRESS)));
        	return new AlertDialog.Builder(SettingActivity.this)
        	.setTitle(R.string.website_title)
        	.setView(mTextEntryView)
            .setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    /* User clicked OK so do some stuff */
                	if(!mEditAdress.getText().toString().equals(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, ConfigInfo.COMM.CONST_SERVER_ADDRESS)))){
                		new AsyncDataLoader(asyncRemoteCallback,mctx,mCheck_url,"","",mEditAdress.getText().toString()).execute();
                	}
                }
            }).setNegativeButton(R.string.btn_cancle, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked cancel so do some stuff */
                }
            }).create();
        	default:
        		break;
        }
        return null;
        }
        	
	
	@Override
	protected void onResume() {
		super.onResume();
		Log(TAG + "SettingActivity onResume()");
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log(TAG + "SettingActivity onStop()");
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log(TAG + "SettingActivity destory()");
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {// 捕捉返回键
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			ConfirmExit();// 按了返回键，但已经不能返回，则执行退出确认
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void ConfirmExit() {// 退出确认
		AlertDialog.Builder dialog = new AlertDialog.Builder(SettingActivity.this);
		dialog.setTitle(mctx.getString(R.string.exit));
		dialog.setMessage(mctx.getString(R.string.is_exit_weibo));
		dialog.setPositiveButton(mctx.getString(R.string.btn_ok), new DialogInterface.OnClickListener() {// 退出按钮
					@Override
					public void onClick(DialogInterface dialog, int i) {
						// TODO Auto-generated method stub
						SettingActivity.this.finish();// 关闭activity
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				});
		dialog.setNegativeButton(mctx.getString(R.string.btn_cancle), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int i) {
				// 不退出不用执行任何操作
			}
		});
		dialog.show();// 显示对话框
	}
	
	void Log(String msg) {
		Log.e(TAG, "SettingActivity--" + msg);
	}
	
	/**
	 * 异步加载服务器上的微博数据的监听器,check_url
	 */
	private AsyncDataLoader.Callback asyncRemoteCallback = new AsyncDataLoader.Callback() {
		
		private boolean mRet = false;
		private String mNewUrl = null;

		@Override
		public void onStart(String address, String more) {
			// TODO Auto-generated method stub
			StringBuffer url = new StringBuffer();
//			url.append(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, mPrefs
//					.getString(ConfigInfo.PREF_SERVER_ADDRESS,
//							ConfigInfo.COMM.CONST_SERVER_ADDRESS)));
			mNewUrl = more;
			url.append(more);
			url.append(address);
			url.append(ConfigInfo.COMM.APY_KEY);
			
			mRet = HttpUtils.check_url(url.toString());
			
			Log(TAG + " in the  asyncRemoteCallback onStart() , mRet = " + mRet);
			Log(TAG + " in the  check url address =  " + address);
			Log(TAG + " in the  check url =  " + url.toString());
			
		}
		
		@Override
		public void onStart(String address, String arg1, String arg2) {
			// TODO Auto-generated method stub
			
		}
		@Override
		public void onFinish() {
			// TODO Auto-generated method stub
			if(mRet){
				if(!mNewUrl.equals(mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, ConfigInfo.COMM.CONST_SERVER_ADDRESS))){
					exitApp();
				}
				SharedPreferences.Editor editor = mPrefs.edit();
				editor.putString(ConfigInfo.PREF_SERVER_ADDRESS, mEditAdress.getText().toString());
				editor.commit();
				Toast.makeText(mctx, mctx.getString(R.string.modify_url_pass), 1).show();
				Log.e(TAG," mNewUrl = " + mNewUrl);
				Log.e(TAG," pref = " + mPrefs.getString(ConfigInfo.PREF_SERVER_ADDRESS, ConfigInfo.COMM.CONST_SERVER_ADDRESS));
			}else{
				Toast.makeText(mctx, mctx.getString(R.string.modify_url_fail), 1).show();
			}
			
		}

		@Override
		public void onPrepare() {
			// TODO Auto-generated method stub
			
		}

		
	};
	
	private class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private Bitmap arrayIcon[] = {
        		 BitmapFactory.decodeResource(mctx.getResources(), R.drawable.wrench),
        		 BitmapFactory.decodeResource(mctx.getResources(), R.drawable.about),
        		 BitmapFactory.decodeResource(mctx.getResources(), R.drawable.logout)};
    	private String[] DATA = {
    			mctx.getResources().getString(R.string.website_address ),
    			mctx.getResources().getString(R.string.about),
    			mctx.getResources().getString(R.string.exit )};

        public EfficientAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return DATA.length;
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return position;
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.setting_item, null);
                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.icon.setScaleType(ScaleType.CENTER_INSIDE);
                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            Log.e(TAG,ConfigInfo.IS_LOGOUT?"lgoout:true":"logout:false");
            if(ConfigInfo.IS_LOGOUT && 2 == position){
            	holder.text.setText(mctx.getString(R.string.login));
            	Log.e(TAG," login here ................................  ");
            }else{
            	holder.text.setText(DATA[position]);
            }
//            holder.text.setText(DATA[position]);
            holder.icon.setImageBitmap(arrayIcon[position]);
            return convertView;
        }

        class ViewHolder {
            TextView text;
            ImageView icon;
        }
    }
}
